import {
  formatTime
} from '../../utils/util.js'
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    pageNum: 1,
    pageSize: 10,
    isRequest: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getHistoryList();
  },
  getHistoryList() {
    if (!this.data.isRequest) return;
    app.fetchRequest({
      url: `/course/watch/history`,
      data: {
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize
      },
      success: (res) => {
        wx.stopPullDownRefresh();
        if (res.list.length) {
          res.list.forEach(item => {
            item.watchTime = formatTime(new Date(item.watchTime));
          })
          if (this.data.list.length) {
            this.data.list.push(...res.list)
            this.setData({
              list: this.data.list,
              pageNum: ++this.data.pageNum
            })
          } else {
            this.setData({
              list: res.list,
              pageNum: ++this.data.pageNum
            })
          }
        } else {
          this.setData({
            isRequest: false
          })
        }
      }
    })
  },
  watch(e) {
    const item = e.currentTarget.dataset.item;
    const url = item.video.videoLink;
    const videoId = item.video.id;

    wx.navigateTo({
      url: `../video/video?url=${url}&videoId=${videoId}`,
    })
  },
  onReachBottom() {
    this.getHistoryList();
  },
  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      list: [],
      isRequest: true
    });
    this.getHistoryList();
  }
})